import {AxiosHeaders, AxiosResponse} from "axios";
import HttpClient from "./http-client.js";
import {RequestConfig,} from "./http-client-type.js";
import HttpClientUtil from "./http-client-util.js";

let authenticationSuccess = true;

/**
 * 响应成功拦截器，2xx范围内的状态码都会触发该函数。不能使用箭头函数，否则无this
 * @param axiosResponse {
 *  status: 来自服务器响应的HTTP状态码
 *  statusText: 来自服务器响应的HTTP状态信息
 *  data: 由服务器提供的响应
 *  headers: 服务器响应头。header名都是小写，而且可以使用方括号语法访问，例如`response.headers['content-type']`
 *  config: axios的请求配置信息
 *  request: 生成此响应的请求。Nodejs中为最后一个ClientRequest实例，浏览器中为XMLHttpRequest实例
 * }
 */
const handleResponseFulfilled = function handleResponseFulfilled(
    this: HttpClient,
    axiosResponse: AxiosResponse
) {
  // log.debug("AxiosResponse：{}", axiosResponse);

  const requestConfig = axiosResponse.config as RequestConfig<any>;
  const responseBody = axiosResponse.data;
  const responseHeaders = axiosResponse.headers as AxiosHeaders;

  // loading
  const showLoading =
      typeof requestConfig.showLoading === "function"
          ? requestConfig.showLoading()
          : requestConfig.showLoading;

  // 被传递的数据
  const passedData = requestConfig.passCompleteResponse
      ? axiosResponse
      : responseBody;

  // 非json数据
  const contentTypeObj = responseHeaders.get("content-type", true);
  if (!Object.hasOwn(contentTypeObj as object, "application/json")) {
    if (showLoading) {
      requestConfig.hideLoadingFunction(true);
    }
    return Promise.resolve(passedData);
  }

  // 文本数据
  if (requestConfig.responseType === "text") {
    if (showLoading) {
      requestConfig.hideLoadingFunction(true);
    }
    return Promise.resolve(passedData);
  }

  // json数据
  // 业务判定
  let isServerSuccess = false;
  if (HttpClientUtil.isMocked(requestConfig, this.mockConfig)) {
    isServerSuccess = true;
  } else {
    isServerSuccess =
        typeof requestConfig.serverResponseSuccess === "function"
            ? requestConfig.serverResponseSuccess(responseBody)
            : requestConfig.serverResponseSuccess;
  }

  if (showLoading) {
    requestConfig.hideLoadingFunction(isServerSuccess);
  }

  // 业务成功
  if (isServerSuccess) {
    // log.debug("业务成功");
    const showSuccessMsg =
        typeof requestConfig.showSuccessMsg === "function"
            ? requestConfig.showSuccessMsg()
            : requestConfig.showSuccessMsg;
    if (showSuccessMsg) {
      requestConfig.showSuccessMsgFunction(
          requestConfig.successMsg(responseBody)
      );
    }
    return Promise.resolve(passedData);
  }

  // 业务失败
  // log.debug("业务失败");
  const showFailureMsg =
      typeof requestConfig.showFailureMsg === "function"
          ? requestConfig.showFailureMsg()
          : requestConfig.showFailureMsg;

  // 如果是认证失败错误，只显示一次错误消息，避免重复显示多条认证失败错误
  if (showFailureMsg && authenticationSuccess) {
    requestConfig.showFailureMsgFunction(
        requestConfig.failureMsg(responseBody)
    );
  }

  const authenticationFailure =
      typeof requestConfig.authenticationFailure === "function"
          ? requestConfig.authenticationFailure(responseBody)
          : requestConfig.authenticationFailure;
  if (authenticationFailure) {
    authenticationSuccess = false;
    requestConfig.handleAuthenticationFailure();
  } else {
    authenticationSuccess = true;
  }

  return Promise.reject(passedData);
};

export default handleResponseFulfilled;
